<!--
 * @author dumeng
 页面信息管理
 -->
<template>
  <div id="page-info">
    <el-collapse-transition>
      <div v-show="searchshow" class="course-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.commonParam"
          placeholder="请输入关键字搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">描述</div>
                <el-input
                  v-model.trim="search.remark"
                  style="width: 80%"
                  class="filter-item"
                  placeholder="请输入描述搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">页面标识</div>
                <el-input
                  v-model.trim="search.pageFlag"
                  placeholder="请输入页面标识搜索"
                  class="search-input"
                  @keyup.enter.native="handleFilter"
                />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <div class="btn-container">
      <div class="btn-container-title">
        <span>页面信息管理</span>
      </div>
      <div class="btn-container-btns">
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新建</el-button>
        <el-dropdown split-button :hide-on-click="false" style="margin-left: 10px;">
          标题设置
          <el-dropdown-menu slot="dropdown">
            <el-checkbox-group v-model="checkboxarr">
              <el-tooltip class="item" effect="dark" content="鼠标点击标题拖动可以调整标题显示顺序" placement="left">
                <draggable :list="tablecolumn" :animation="340" group="column" @end="onEnd">
                  <div v-for="item in tablecolumn" :key="item.prop" class="column-item">
                    <el-dropdown-item>
                      <el-checkbox :label="item.prop">{{ item.label }}</el-checkbox>
                    </el-dropdown-item>
                  </div>
                </draggable>
              </el-tooltip>
            </el-checkbox-group>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="table">
      <el-table
        ref="rolemantable"
        :key="key"
        v-loading="listLoading"
        border
        fit
        :data="list"
        class="tableScope"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-for="item in column"
          :key="item"
          :label="getLabel(item)"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">{{ scope.row[item] }}</template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      center
      width="800px"
    >
      <el-form
        ref="addForm"
        v-loading="submitloading"
        :model="addForm"
        :rules="addRules"
        class="dataForm"
        label-position="right"
        label-width="80px"
        style="height:410px"
      >
        <el-form-item label="描述" prop="remark">
          <el-input v-model.trim="addForm.remark" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item :disabled="dialogStatus === 'update'" label="页面标识" prop="pageFlag">
          <el-input v-model.trim="addForm.pageFlag" placeholder="请输入页面标识" />
        </el-form-item>
        <el-form-item label="JSON配置" prop="jsonData">
          <el-input
            v-model.trim="addForm.jsonData"
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 12}"
            placeholder="请输入JSON配置"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 10px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  queryPage,
  addOrUpd,
  get,
  del
} from '@/views/pageinfo/api/index'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
// eslint-disable-next-line no-unused-vars
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import draggable from 'vuedraggable'

export default {
  name: 'Pageinfo',
  components: { Pagination, draggable },
  directives: { permission, elDragDialog },
  data() {
    function JSONTest(rule, value, callback) {
      if (!value) {
        callback(new Error('请填写JSON配置'))
      } else {
        try {
          const jsonparse = JSON.parse(value)
          if (jsonparse.length === 0) {
            callback(new Error('JSON配置不能为空'))
            return
          }
          if (jsonparse.every(item => item.hasOwnProperty('label') &&
            item.hasOwnProperty('prop') &&
            item.hasOwnProperty('isShow'))) {
            if (jsonparse.every(item => item['label'] && item['prop'] && (item['isShow'] === true || item['isShow'] === false))) {
              jsonparse.forEach(item => {
                if (jsonparse.filter(ite => ite['label'] === item['label']).length > 1) {
                  callback(new Error('JSON中label字段值重复'))
                  return
                } else if (jsonparse.filter(ite => ite['prop'] === item['prop']).length > 1) {
                  callback(new Error('JSON中prop字段值重复'))
                  return
                }
              })
            } else {
              callback(new Error('JSON中字段值不正确'))
              return
            }
          } else {
            callback(new Error('JSON中字段不正确'))
            return
          }
        } catch (err) {
          callback(new Error('请填写正确的JSON格式'))
          return
        }
      }
      callback()
    }

    return {
      key: 1,
      checkboxarr: [
        'remark',
        'pageFlag',
        'jsonData'
      ],
      column: [
        'remark',
        'pageFlag',
        'jsonData'
      ],
      tablecolumn: [
        {
          prop: 'remark',
          label: '描述',
          isShow: true
        },
        {
          prop: 'pageFlag',
          label: '页面标识',
          isShow: true
        },
        {
          prop: 'jsonData',
          label: 'JSON配置',
          isShow: true
        }

      ],
      submitloading: false,
      listQuery: {
        userId: -1,
        commonParam: '',
        page: 1,
        pageSize: 10
      },
      addForm: {
        userId: -1,
        pageFlag: '',
        jsonData: '',
        remark: ''
      },
      searchshow: true,
      search: {
        pageFlag: '',
        remark: ''
      },
      list: [],
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '新建',
        update: '编辑'
      },
      multipleSelection: [],
      listLoading: false,
      addRules: {
        pageFlag: [
          { required: true, message: '请填写页面标识', trigger: 'blur' }
        ],
        jsonData: [
          { required: true, message: '请填写JSON配置', trigger: 'blur' },
          { validator: JSONTest, trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请填写页面描述', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    checkboxarr(arr) {
      const a = this.tablecolumn.filter(i => arr.indexOf(i.prop) >= 0)
      const b = []
      a.forEach(item => {
        b.push(item.prop)
      })
      this.column = Object.assign([], b)
      this.key = this.key + 1// 为了保证table 每次都会重渲
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.getList()
  },
  methods: {
    onEnd() {
      const a = this.tablecolumn.filter(i => this.checkboxarr.indexOf(i.prop) >= 0)
      const b = []
      a.forEach(item => {
        b.push(item.prop)
      })
      this.column = Object.assign([], b)
      this.key = this.key + 1// 为了保证table 每次都会重渲
    },
    getLabel(prop) {
      return this.tablecolumn.find(item => item.prop === prop).label
    },
    filtercolumn(scope, item) {
      if (item === 'userIdnumber' || item === 'phoneNumber') {
        return CryptoJS.$aesJieM(scope.row[item])
      } else {
        return scope.row[item]
      }
    },
    getList(obj) {
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.pageSize,
        userId: this.listQuery.userId
      }
      if (this.searchshow) {
        query['commonParam'] = this.listQuery.commonParam
      } else {
        query['pageFlag'] = this.search.pageFlag
        query['remark'] = this.search.remark
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query).then(res => {
          this.listLoading = false
          this.list = res.data.data.rows || []
          this.total = res.data.data.total
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.listQuery.page = 1
      this.listQuery.pageSize = 10
      this.listQuery.commonParam = ''
      for (const key in this.search) {
        this.search[key] = ''
      }
      this.getList()
    },
    handleCreate() {
      this.dialogStatus = 'create'
      for (const key in this.addForm) {
        if (key !== 'userId') {
          this.addForm[key] = ''
        }
      }
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: row.id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.addForm) {
            this.addForm[key] = data[key]
          }
          this.addForm.id = data.id
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['addForm'].clearValidate()
          })
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        const ids = arr.join(',')
        this.deleteUser(ids)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleDelete(row) {
      this.deleteUser(row.id)
    },
    deleteUser(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del({ ids: ids }).then(res => {
            this.$message.success('删除成功!')
            this.getList()
          })
        })
        .catch(() => {
        })
    },
    createData() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          addOrUpd(this.addForm).then(res => {
            loading.close()
            this.$message.success('创建成功！')
            this.dialogFormVisible = false
            this.listQuery.size = 1
            this.getList()
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            loading.close()
          })
        }
      })
    },
    updateData() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          addOrUpd(this.addForm)
            .then(res => {
              loading.close()
              this.$message.success('编辑成功！')
              this.dialogFormVisible = false
              this.listQuery.size = 1
              this.getList()
            })
            // eslint-disable-next-line handle-callback-err
            .catch(err => {
              loading.close()
            })
        }
      })
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
// $mainColor: #18a5fd;
#page-info {
  padding: 10px 20px 10px 10px;
  .course-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .course-search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .course-search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .btn-container {
    display: flex;
    align-items: center;
    margin-top: 5px;
    margin-bottom: 5px;
    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
  .dataForm {
    .el-radio__label {
      display: inline-block;
      max-width: 380px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
  .el-checkbox__label {
    font-weight: 400;
  }
  .el-form-item__label {
    width: 90px !important;
  }
  .el-form-item__content {
    margin-left: 90px !important;
  }
}
</style>
